import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hive/hive.dart';
import 'package:zywz/bloc/report/report_data.dart';

import '../../api/api_client.dart';
import '../../models/user.dart';
import 'report_event.dart';
 

class ReportBloc extends Bloc<ReportEvent, ReportState> {
  final ApiClient apiClient;
  late final Box<User> userBox;
  ReportBloc({required this.apiClient}) : super(ReportInitial()) {
    userBox = Hive.box<User>('user_box');
    on<LoadReportData>(_onLoadReportData);
    on<LoadReportIncomeData>(_onGetReportformIncome);
    on<LoadReportBalanceData>(_onGetReportformBalance);
    on<LoadReportBalanceQyZwData>(_onGetReportformBalanceQyZw);
    on<ReportChartEvent>(_onReportChartEvent);
  }


  Future<void> _onLoadReportData(LoadReportData event, Emitter<ReportState> emit) async {
    emit(ReportLoading());
    try {
      final data = await apiClient.getReportformTax(userBox?.get('currentUser')?.appCompanyDto?.taxCode ?? '',event.startPeriod,event.endPeriod);
      emit(ReportTaxReportSuccess(data?.data ?? {}));
    } catch (e) {
      emit(ReportLoadFailure(e.toString()));
    }
  }

  Future<void> _onGetReportformIncome(LoadReportIncomeData event, Emitter<ReportState> emit) async {
    emit(ReportLoading());
    try {
      final data = await apiClient.getReportformIncome(userBox?.get('currentUser')?.appCompanyDto?.taxCode ?? '',event.startPeriod,event.endPeriod);
      emit(ReportIncomeReportSuccess(data?.data ?? []));
    } catch (e) {
      emit(ReportLoadFailure(e.toString()));
    }
  }

  Future<void> _onGetReportformBalance(LoadReportBalanceData event, Emitter<ReportState> emit) async {

    try {
      final data = await apiClient.getReportformBalanceSheet(userBox?.get('currentUser')?.appCompanyDto?.taxCode ?? '',event.type,event.startPeriod,event.endPeriod);
      emit(ReportBalanceReportSuccess(data?.data ?? []));
    } catch (e) {
      emit(ReportBalanceReportSuccess([]));
    }
  }

  Future<void> _onGetReportformBalanceQyZw(LoadReportBalanceQyZwData event, Emitter<ReportState> emit) async {

    try {
      final data = await apiClient.getReportformBalanceSheet(userBox?.get('currentUser')?.appCompanyDto?.taxCode ?? '',event.type,event.startPeriod,event.endPeriod);
      emit(ReportBalanceQyZwReportSuccess(data?.data ?? []));
    } catch (e) {
      emit(ReportBalanceQyZwReportSuccess([]));
    }
  }

  Future<void> _onReportChartEvent(ReportChartEvent event, Emitter<ReportState> emit) async {
    try {
      final data = await apiClient.getReportformTecharts(userBox?.get('currentUser')?.appCompanyDto?.taxCode ?? '',event.year.toString());
      emit(ReportChartSuccess(data?.data ?? {}));
    } catch (e) {
      emit(ReportChartSuccess({}));
    }
  }
}